package com.cloudspace.jindun.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author mei
 */
public class BitmapUtil {
    public static final int DEFAULT_WIDHT = 2048;
    public static final int DEFAULT_HIGHT = 2048;
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		
		int height = options.outHeight;
		int width = options.outWidth;
		int inSampleSize = 1;
		int heightRatio = Math.round((float) height/ (float) reqHeight);
		int widthRatio = Math.round((float) width / (float) reqWidth);

		if (height > reqHeight || width > reqWidth) {
			inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
		}
		return initSample(inSampleSize);
	}
	
	public static int initSample(int inSampleSize){
		if(inSampleSize<=1){
			return 1;
		}else if(inSampleSize==2){
			return 2;
		}else if(inSampleSize<2*2){
			return 2*2;
		}else{
			return 2*2*2;
		}
	}

    public static Bitmap getThumbnail(Activity activity,long photoId,String filePath){
        Bitmap bmp = MediaStore.Images.Thumbnails.getThumbnail(activity.getContentResolver(), photoId, MediaStore.Images.Thumbnails.MICRO_KIND, null);
        int angle = readPictureDegree(filePath);
        if (angle != 0) {
            bmp = rotateBitmap(bmp, angle);
        }
        return bmp;
    }

	public static Bitmap getSmallBitmap(String filePath) {
		return getSmallBitmap(filePath,1440,2560);
	}

	public static Bitmap getSmallBitmap(String filePath,int with,int height) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		options.inSampleSize = calculateInSampleSize(options, with, height);

		options.inJustDecodeBounds = false;

		Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
        if(bmp == null){
            try{
                byte[] data = getBytes(new URL(filePath).openStream());
                bmp = BitmapFactory.decodeByteArray(data,0,data.length,options);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
		int angle = readPictureDegree(filePath);
		if (angle != 0) {
			bmp = rotateBitmap(bmp, angle);
		}
		return bmp;
	}

    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用数据装
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        return outstream.toByteArray();
    }

    @SuppressLint("NewApi")
	public static String bitmapToString(String filePath) {
        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);//bm.compress()方法进行压缩，这个方法的第二个参数，如果是100，表示不压缩
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

	public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * @param q 如果是100，表示不压缩
	 * @return
	 */
	public static String compressImage(Context context,
									   String filePath,File target,int q) throws FileNotFoundException {
        Bitmap bmp = getSmallBitmap(filePath);
		if (bmp!=null) {
			return compressImage(context, bmp, target, q);
		}else {
			return null;
		}
    }

	public static String compressImage(Context context,Bitmap bmp,
									   File target,int q) throws FileNotFoundException {
        FileOutputStream out = new FileOutputStream(target);
        bmp.compress(Bitmap.CompressFormat.JPEG,
				q,
				out);//bm.compress()方法进行压缩，这个方法的第二个参数，如果是100，表示不压缩
        return target.getPath();
    }

	public static String compressImage(Context context,Bitmap bmp,
									   String filePath,int q) throws FileNotFoundException {
		FileUtil.checkFile(filePath);
		FileOutputStream out = new FileOutputStream(filePath);
		bmp.compress(Bitmap.CompressFormat.JPEG,
				q,
				out);//bm.compress()方法进行压缩，这个方法的第二个参数，如果是100，表示不压缩
		return filePath;
	}

	/**
	 * 图片合成
	 * @return
	 */
	public static Bitmap createBitmap(Bitmap src, Bitmap watermark) {
		if (src == null) {
			return null;
		}
		int w = src.getWidth();
		int h = src.getHeight();
		int ww = watermark.getWidth();
		int wh = watermark.getHeight();
		// create the new blank bitmap
		Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		Canvas cv = new Canvas(newb);
		// draw src into
		cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
		// draw watermark into
		cv.drawBitmap(watermark, (w - ww)/2, (h - wh)/2, null);// 在src的右下角画入水印
		// save all clip
		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		// store
		cv.restore();// 存储
		return newb;
	}

	/**
	 * 图片圆角
	* @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = 12;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}



	/**
	 * 缩放、翻转和旋转图片
	* @param bmpOrg
	 * @param rotate
	 * @return
	 */
	public static Bitmap gerZoomRotateBitmap(Bitmap bmpOrg, int rotate) {
		// 获取图片的原始的大小
		int width = bmpOrg.getWidth();
		int height = bmpOrg.getHeight();

		int newWidth = 300;
		int newheight = 300;
		// 定义缩放的高和宽的比例
		float sw = ((float) newWidth) / width;
		float sh = ((float) newheight) / height;
		// 创建操作图片的用的Matrix对象
		Matrix matrix = new Matrix();
		// 缩放翻转图片的动作
		// sw sh的绝对值为绽放宽高的比例，sw为负数表示X方向翻转，sh为负数表示Y方向翻转
		matrix.postScale(sw, sh);
		// 旋转30*
		matrix.postRotate(rotate);
		// 创建一个新的图片
		Bitmap resizeBitmap = Bitmap
				.createBitmap(bmpOrg, 0, 0, width, height, matrix, true);
		return resizeBitmap;
	}


	/**
	 *
	 * 将位图对象转换为字节数组
	 * @param bitmap
	 * @return
	 */
	private static byte[] Bitmap2Bytes(Bitmap bitmap) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
		return outputStream.toByteArray();
	}

	/**
	 * 保存二维码至SD卡
	 * @param bitmap
	 */
	public static void saveToSDCard(Bitmap bitmap,File file) throws Exception {
		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(Bitmap2Bytes(bitmap));
		outStream.close();
	}

	/**
	 * 截圆图
	 * @return
	 */
	public static Bitmap takeViewRoundShot(View view,int left,int top,int radius) {
        // View是你需要截图的View
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
		return toRoundBitmap(bitmap,left,top,radius);
	}

    /**
     *截圆图，从左last_left，上last_top开始截图
     * @param bitmap
     * @param radius 直径
     * @return
     */
	public static Bitmap toRoundBitmap(Bitmap bitmap,int left,int top,int radius) {
		float roundPx;
		float right, bottom;
		roundPx = radius / 2;
		right = left+radius;
		bottom = top+radius;

		Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		Paint paint = new Paint();
		Rect src = new Rect((int) left, (int) top, (int) right,(int) bottom);
		Rect dst = new Rect((int) 0, (int) 0,(int) radius, (int) radius);
		RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}

	/**
	 * 截正方形图（截正中心）
	 * @return
	 */
	public static Bitmap toSquireBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int squire_width;
		float left, top, right, bottom;
		if (width <= height) {
			squire_width = width;
			float clip = (height - width) / 2;
			top = clip;
			bottom = height - clip;
			left = 0;
			right = width;
		} else {
			squire_width = height;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
		}
		Bitmap output = Bitmap.createBitmap(squire_width, squire_width, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		Paint paint = new Paint();
		Rect src = new Rect((int) left, (int) top, (int) right,(int) bottom);
		Rect dst = new Rect(0, 0,squire_width, squire_width);
		RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		canvas.drawRect(rectF, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}

    /**
     * 截图
     * @return
     */
    public static Bitmap toCropBitmap(Bitmap bitmap,int crop_left,int crop_top,int crop_right,int crop_bottom) {
        int crop_width = crop_right-crop_left;
        int crop_height = crop_bottom - crop_top;

        Bitmap output = Bitmap.createBitmap(crop_width, crop_height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        Rect src = new Rect((int) crop_left, (int) crop_top, (int) crop_right,(int) crop_bottom);
        Rect dst = new Rect(0, 0,crop_width, crop_height);
        RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRect(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }


}
